package com.example.servlet.auth;

import com.example.entity.Passenger;
import com.example.service.UserService;
import com.example.service.impl.UserServiceImpl;
import com.example.utils.BCryptUtil;
import com.example.utils.MybatisUtil;
import com.example.utils.ThymeleafUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@WebServlet("/user_register")
public class RegisterServlet extends HttpServlet {

    private UserService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new UserServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Context context = new Context();
        if (req.getSession().getAttribute("register-failure") != null) {
            context.setVariable("failure", true);
            req.getSession().removeAttribute("register-failure");
        }
        if (req.getSession().getAttribute("Account-failure") != null) {
            context.setVariable("account_failure", true);
            req.getSession().removeAttribute("Account-failure");
        }
        if (req.getSession().getAttribute("IDcard-failure") != null) {
            context.setVariable("IDcard_failure", true);
            req.getSession().removeAttribute("IDcard-failure");
        }
        if (req.getSession().getAttribute("Phone-failure") != null) {
            context.setVariable("phone_failure", true);
            req.getSession().removeAttribute("Phone-failure");
        }
        if (req.getSession().getAttribute("Password-failure") != null) {
            context.setVariable("password_failure", true);
            req.getSession().removeAttribute("Password-failure");
        }
        ThymeleafUtil.process("user_register.html", context, resp.getWriter());
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String sex = req.getParameter("sex");
        String ID_type = req.getParameter("ID_type");
        String ID_card = req.getParameter("ID_card");
        String birthday = req.getParameter("birthday");
        String account = req.getParameter("account");
        String password1 = req.getParameter("password1");
        String password2 = req.getParameter("password2");
        String phone = req.getParameter("phone");

        try {
            // 检查账户是否存在
            if (service.isExistByAccount(account) == 1) {
                req.getSession().setAttribute("Account-failure", new Object());
                this.doGet(req, resp);
                return;
            }
            // 检查证件是否存在
            if (service.isExistByIDcardAndIDtype(ID_type, ID_card) == 1) {
                req.getSession().setAttribute("IDcard-failure", new Object());
                this.doGet(req, resp);
                return;
            }
            // 检查手机号是否存在
            if (service.isExistByPhone(phone) == 1) {
                req.getSession().setAttribute("Phone-failure", new Object());
                this.doGet(req, resp);
                return;
            }
            // 检查密码是否一致
            if(!password1.equals(password2)){
                req.getSession().setAttribute("Password-failure", new Object());
                this.doGet(req, resp);
                return;
            }

            Passenger passenger = service.getPassengerByIDtypeAndIDcard(ID_type, ID_card);
            if (passenger != null) {
                if ((!passenger.getPassenger_ID_card().equals(ID_card) && !passenger.getID_type().equals(ID_type)) || !passenger.getPassenger_name().equals(name) || !passenger.getPassenger_sex().equals(sex)) {
                    req.getSession().setAttribute("register-failure", new Object());
                    this.doGet(req, resp);
                    return;
                }
            } else {
                if (service.addPassenger(name, sex, ID_type, ID_card, birthday) == 0) {
                    throw new Exception("Failed to add user");
                }
            }
            // 添加用户
            String today = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE);
            String hashedPassword = BCryptUtil.encryptPassword(password1); // 加密密码
            if (service.addUser(name, sex, ID_type, ID_card, account, hashedPassword, phone, birthday,today) == 0) {
                throw new Exception("Failed to add user");
            }
            if (service.addBank(name, ID_type, ID_card) == 0) {
                throw new Exception("Failed to add bank");
            }
            // 提交事务
            service.commit();
            // 注册成功
            req.getSession().setAttribute("register-success", true);
            resp.sendRedirect("user_login");
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            service.rollback();
            req.getSession().setAttribute("register-failure", new Object());
            this.doGet(req, resp);
        }
    }
}
